package com.tangly.codeing.config;

import com.alibaba.fastjson.JSONObject;
import com.tangly.codeing.model.SysUser;
import com.tangly.codeing.service.SysUserService;
import com.tangly.codeing.utils.JWT;
import com.tangly.codeing.utils.ReturnT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 统一请求拦截，验证token
 *
 * @author tangbing
 * @date 2019/5/10
 */
@ConfigurationProperties(prefix = "auth")
public class AuthenticationInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(AuthenticationInterceptor.class);

    @Autowired
    SysUserService sysUserService;

    private List<String> openUrls;

    public List<String> getOpenUrls() {
        return openUrls;
    }

    public void setOpenUrls(List<String> openUrls) {
        this.openUrls = openUrls;
    }

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        /*if (isOpenUrl(httpServletRequest.getRequestURI())) {
            return true;
        }
        // 从 http 请求头中取出 token
        String token = httpServletRequest.getHeader("Authorization");
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        // 执行认证
        if (token == null) {
            return returnJson(httpServletResponse, "无token，请重新登录");
        }
        // 获取 token 中的 user id
        String uuid;
        try {
            uuid = JWT.unsign(token, String.class);
        } catch (Exception j) {
            return returnJson(httpServletResponse, "token解析失败");
        }
        SysUser user = sysUserService.findByUuid(uuid);
        if (user == null) {
            return returnJson(httpServletResponse, "用户不存在，请重新登录");
        }*/
        return true;
    }

    private boolean returnJson(HttpServletResponse response, String msg) throws Exception {
        ReturnT returnT = new ReturnT<>(ReturnT.FAIL_TOKEN_CODE, msg);
        String json = JSONObject.toJSONString(returnT);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(json);
        } catch (IOException e) {
            logger.error("response error", e);
        }
        return false;
    }

    boolean isOpenUrl(String userAccessUrl) {
        for (String url : openUrls) {
            if (userAccessUrl.matches(url)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) {
    }
}